package com.alibaba.algo.apiimpl.user;

import com.alibaba.algo.constants.Constants;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.feign.vo.req.SelectGroupPageRequestVO;
import com.alibaba.algo.cooperation.feign.vo.req.SelectUserInfoReqVO;
import com.alibaba.algo.cooperation.feign.vo.res.RpcUserInfoVO;
import com.alibaba.algo.cooperation.feign.vo.res.UserEmployeeResVO;
import com.alibaba.algo.cooperation.feign.vo.res.UserGroupResVO;
import com.alibaba.algo.cooperation.feign.vo.res.UserOrgResVO;
import com.alibaba.algo.cooperation.feign.vo.res.UserPositionResVO;
import com.alibaba.algo.cooperation.feign.vo.res.UserRoleInfoResVO;
import com.alibaba.algo.cooperation.feign.vo.res.UserRoleResVO;
import com.alibaba.algo.cooperation.usercomponent.service.user.SysUserCacheService;
import com.alibaba.algo.cooperation.usercomponent.vo.req.cache.CacheRequestVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.EmployeeOrgResVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.EmployeePositionResVO;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.domain.user.SysCurrentOrgDomain;
import com.alibaba.algo.domain.user.SysEmployeeGroupDomain;
import com.alibaba.algo.domain.user.SysEmployeeOrgDomain;
import com.alibaba.algo.domain.user.SysEmployeePositionDomain;
import com.alibaba.algo.domain.user.SysGroupDomain;
import com.alibaba.algo.domain.user.SysOrgDomain;
import com.alibaba.algo.domain.user.SysOrgGroupDomain;
import com.alibaba.algo.domain.user.SysUserCacheDomain;
import com.alibaba.algo.domain.user.SysUserDomain;
import com.alibaba.algo.domain.user.SysUserEmployeeDomain;
import com.alibaba.algo.domain.user.SysUserRoleDomain;
import com.alibaba.algo.entity.user.SysCurrentOrg;
import com.alibaba.algo.entity.user.SysEmployee;
import com.alibaba.algo.entity.user.SysGroup;
import com.alibaba.algo.entity.user.SysOrg;
import com.alibaba.algo.entity.user.SysOrgGroup;
import com.alibaba.algo.entity.user.SysUser;
import com.alibaba.algo.entity.user.SysUserCache;
import com.alibaba.algo.enums.SysUserCacheStatusEnum;
import com.alibaba.algo.utils.CacheUtil;
import com.alibaba.algo.utils.JedisUtil;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@RefreshScope
@Slf4j
@RestController
public class SysUserCacheServiceImpl implements SysUserCacheService {

    @Value("${apiCacheSwitch.qryUserInfo:N}")
    private String qryUserInfoCacheSwitch;

    @Autowired
    private SysUserDomain sysUserDomain;
    @Autowired
    private SysUserRoleDomain sysUserRoleDomain;
    @Autowired
    private SysUserEmployeeDomain sysUserEmployeeDomain;
    @Autowired
    private SysEmployeePositionDomain sysEmployeePositionDomain;
    @Autowired
    private SysEmployeeOrgDomain sysEmployeeOrgDomain;
    @Autowired
    private SysEmployeeGroupDomain sysEmployeeGroupDomain;
    @Autowired
    private SysCurrentOrgDomain sysCurrentOrgDomain;
    @Autowired
    private SysGroupDomain sysGroupDomain;
    @Autowired
    private SysUserCacheDomain sysUserCacheDomain;
    @Autowired
    private SysOrgDomain sysOrgDomain;
    @Autowired
    private SysOrgGroupDomain sysOrgGroupDomain;

    /**
     * 判断缓存开关是否打开
     *
     * @return
     */
    public boolean isOpenQueryUserCacheSwatch() {
        return YesOrNo.Y.name().equalsIgnoreCase(qryUserInfoCacheSwitch);
    }

    /**
     * 将用户信息放入缓存
     */
    private void putSysUserIntoCache(SysUser sysUser) {
        if (null == sysUser) {
            log.info("putSysUserIntoCache sysUser is null");
            return;
        }

        String redisKey = CacheUtil.getUserInfoUserKey(sysUser.getId());
        // 放入缓存
        //String result = JedisUtil.setObjectValue(redisKey, sysUser, CacheUtil.randomExpireSeconds());
        //log.info("getSysUserFromCache userId:{},userObj:{},result:{}", sysUser.getId(), JSON.toJSONString(sysUser), result);
        CacheUtil.setObjectValueInThread(redisKey, sysUser);
    }

    /**
     * 通过UserId从缓存中取用户信息
     */
    private SysUser getSysUserFromCacheByUserId(Long userId, String isDeleted) {
        SysUser sysUser = null;
        String redisKey = CacheUtil.getUserInfoUserKey(userId);
        Object objectValue = JedisUtil.getObjectValue(redisKey);
        if (null != objectValue) {
            sysUser = (SysUser) objectValue;
            log.info("getSysUserFromCacheByUserId 从缓存获取成功");
        } else {
            sysUser = sysUserDomain.getByIdDefaultAll(userId, isDeleted);
            putSysUserIntoCache(sysUser);
        }
        return sysUser;
    }

    /**
     * 从缓存取用户基本信息
     */
    private SysUser getSysUserFromCache(SelectUserInfoReqVO paramVo) {
        SysUser sysUser = null;
        if (!ObjectUtils.isEmpty(paramVo.getUserId())) {
            sysUser = getSysUserFromCacheByUserId(paramVo.getUserId(), paramVo.getIsDeleted());
        } else if (!ObjectUtils.isEmpty(paramVo.getEmployeeCode())) {
            String userIdMapEmpKey = CacheUtil.getUserIdMapEmpKey(paramVo.getEmployeeCode());
            String userId = JedisUtil.getStringValue(userIdMapEmpKey);
            if (!ObjectUtils.isEmpty(userId)) {
                sysUser = getSysUserFromCacheByUserId(new Long(userId), paramVo.getIsDeleted());
            } else {
                sysUser = sysUserDomain.getOneByEmployeeCodeDefaultAll(paramVo.getEmployeeCode(), paramVo.getIsDeleted());
                if (null != sysUser) {
                    //String result = JedisUtil.setStringValue(userIdMapEmpKey, String.valueOf(sysUser.getId()), CacheUtil.randomExpireSeconds());
                    //log.info("getSysUserFromCache userIdMapEmpKey:{},userId:{},result:{}", userIdMapEmpKey, sysUser.getId(), result);
                    CacheUtil.setStringValueInThread(userIdMapEmpKey, String.valueOf(sysUser.getId()));
                    putSysUserIntoCache(sysUser);
                }
            }
        } else if (!ObjectUtils.isEmpty(paramVo.getUserAccount())) {
            String userIdMapActKey = CacheUtil.getUserIdMapActKey(paramVo.getUserAccount());
            String userId = JedisUtil.getStringValue(userIdMapActKey);
            if (!ObjectUtils.isEmpty(userId)) {
                sysUser = getSysUserFromCacheByUserId(new Long(userId), paramVo.getIsDeleted());
            } else {
                sysUser = sysUserDomain.getByUserAccountDefaultAll(paramVo.getUserAccount(), paramVo.getIsDeleted());
                if (null != sysUser) {
                    //String result = JedisUtil.setStringValue(userIdMapActKey, String.valueOf(sysUser.getId()), CacheUtil.randomExpireSeconds());
                    //log.info("getSysUserFromCache userIdMapActKey:{},userId:{},result:{}", userIdMapActKey, sysUser.getId(), result);
                    CacheUtil.setStringValueInThread(userIdMapActKey, String.valueOf(sysUser.getId()));
                    putSysUserIntoCache(sysUser);
                }
            }
        }
        return sysUser;
    }

    /**
     * 从缓存获取角色清单
     */
    private void getUserRoleFromCache(RpcUserInfoVO rpcUserInfoVO) {
        String redisKey = CacheUtil.getUserInfoRoleKey(rpcUserInfoVO.getUserId());
        Object objectValue = JedisUtil.getObjectValue(redisKey);
        if (null != objectValue) {
            rpcUserInfoVO.setRoleList((List<UserRoleResVO>) objectValue);
            log.info("getUserRoleFromCache 从缓存获取成功");
            return;
        }

        List<UserRoleInfoResVO> userRoleInfoResVOS = sysUserRoleDomain.selectRoleListByUserIdDefaultAll(rpcUserInfoVO.getUserId(), null, rpcUserInfoVO.getIsDeleted());
        List<UserRoleResVO> roleList = new ArrayList<>();
        userRoleInfoResVOS.forEach(userRoleInfoResVO -> {
            UserRoleResVO userRoleResVO = new UserRoleResVO();
            BeanUtils.copyProperties(userRoleInfoResVO, userRoleResVO);
            roleList.add(userRoleResVO);
        });
        rpcUserInfoVO.setRoleList(roleList);

        // 放入缓存
        if (null != roleList && roleList.size() > 0) {
            //String result = JedisUtil.setObjectValue(redisKey, roleList, CacheUtil.randomExpireSeconds());
            //log.info("getSysUserFromCache redisKey:{},roleList:{},result:{}", redisKey, JSON.toJSONString(roleList), result);
            CacheUtil.setObjectValueInThread(redisKey, roleList);
        }
    }

    /**
     * 从缓存获取员工信息
     */
    private void getUserEmployeeFromCache(RpcUserInfoVO rpcUserInfoVO) {
        String redisKey = CacheUtil.getUserInfoEmployeeKey(rpcUserInfoVO.getUserId());
        Object objectValue = JedisUtil.getObjectValue(redisKey);
        if (null != objectValue) {
            rpcUserInfoVO.setEmployeeInfo((UserEmployeeResVO) objectValue);
            log.info("getUserEmployeeFromCache 从缓存获取成功");
            return;
        }

        SysEmployee sysEmployee = sysUserEmployeeDomain.selectEmployeeByUserIdDefaultAll(rpcUserInfoVO.getUserId(), rpcUserInfoVO.getIsDeleted());
        if (null == sysEmployee) {
            return;
        }
        UserEmployeeResVO employeeInfo = new UserEmployeeResVO();
        BeanUtils.copyProperties(sysEmployee, employeeInfo);
        employeeInfo.setEmployeeId(sysEmployee.getId());
        rpcUserInfoVO.setEmployeeInfo(employeeInfo);
        if (StringUtils.isEmpty(rpcUserInfoVO.getEmployeeCode())) {
            rpcUserInfoVO.setEmployeeCode(sysEmployee.getEmployeeCode());
        }

        // 放入缓存
        if (null != employeeInfo) {
            //String result = JedisUtil.setObjectValue(redisKey, employeeInfo, CacheUtil.randomExpireSeconds());
            //log.info("getEmployeeFromCache redisKey:{},employeeInfo:{},result:{}", redisKey, JSON.toJSONString(employeeInfo), result);
            CacheUtil.setObjectValueInThread(redisKey, employeeInfo);
        }
    }

    /**
     * 从缓存获取岗位信息
     */
    private void getUserPositionFromCache(RpcUserInfoVO rpcUserInfoVO) {
        String redisKey = CacheUtil.getUserInfoPositionKey(rpcUserInfoVO.getUserId());
        Object objectValue = JedisUtil.getObjectValue(redisKey);
        if (null != objectValue) {
            List<UserPositionResVO> positionResVOList = (List<UserPositionResVO>) objectValue;
            rpcUserInfoVO.setPositionList(positionResVOList);
            log.info("getUserPositionFromCache 从缓存获取成功");
            return;
        }

        List<UserPositionResVO> positionResVOList = new ArrayList<>();
        List<EmployeePositionResVO> employeePositionResVOList = sysEmployeePositionDomain
                .selectEmployeePositionListByEmployeeIdDefaultAll(rpcUserInfoVO.getEmployeeInfo().getEmployeeId(), rpcUserInfoVO.getEmployeeInfo().getIsDeletedEmployee());
        employeePositionResVOList.forEach(item -> {
            UserPositionResVO positionResVO = new UserPositionResVO();
            positionResVO.setPositionId(item.getEmployeePositionId());
            positionResVO.setPositionName(item.getPositionName());
            positionResVO.setIsDeletedPosition(item.getIsDeletedPosition());
            positionResVO.setIsDeletedEmployeePositionRel(item.getIsDeletedEmployeePositionRel());
            positionResVOList.add(positionResVO);
        });
        rpcUserInfoVO.setPositionList(positionResVOList);

        // 放入缓存
        if (null != positionResVOList && positionResVOList.size() > 0) {
            //String result = JedisUtil.setObjectValue(redisKey, positionResVOList, CacheUtil.randomExpireSeconds());
            //log.info("getPositionFromCache redisKey:{},positionResVOList:{},result:{}", redisKey, JSON.toJSONString(positionResVOList), result);
            CacheUtil.setObjectValueInThread(redisKey, positionResVOList);
        }
    }

    /**
     * 从缓存获取组织信息
     */
    private void getUserOrgFromCache(RpcUserInfoVO rpcUserInfoVO) {
        String redisKey = CacheUtil.getUserInfoOrgKey(rpcUserInfoVO.getUserId());
        Object objectValue = JedisUtil.getObjectValue(redisKey);
        if (null != objectValue) {
            List<UserOrgResVO> userOrgResVOList = (List<UserOrgResVO>) objectValue;
            rpcUserInfoVO.setOrgList(userOrgResVOList);
            log.info("getUserOrgFromCache 从缓存获取成功");
            return;
        }

        List<EmployeeOrgResVO> employeeOrgResVOS = sysEmployeeOrgDomain
                .selectEmployeeOrgListByEmployeeIdDefaultAll(rpcUserInfoVO.getEmployeeInfo().getEmployeeId(), rpcUserInfoVO.getEmployeeInfo().getIsDeletedEmployee());
        List<UserOrgResVO> userOrgResVOList = new ArrayList<>();
        // 默认组织信息
        AtomicReference<UserOrgResVO> primaryOrg = new AtomicReference<>();
        employeeOrgResVOS.forEach(item -> {
            UserOrgResVO userOrgResVO = new UserOrgResVO();
            userOrgResVO.setOrgId(item.getEmployeeOrgId());
            userOrgResVO.setOrgName(item.getOrgName());
            userOrgResVO.setUuid(item.getUuid());
            userOrgResVO.setOrgCode(item.getOrgCode());
            userOrgResVO.setIsPrimaryOrg(item.getIsPrimaryOrg());
            userOrgResVO.setIsDeletedOrg(item.getIsDeletedOrg());
            userOrgResVO.setIsDeletedEmployeeOrgRel(item.getIsDeletedEmployeeOrgRel());
            if (YesOrNo.Y.name().equals(item.getIsPrimaryOrg())) {
                primaryOrg.set(userOrgResVO);
            }
            userOrgResVOList.add(userOrgResVO);
        });
        rpcUserInfoVO.setOrgList(userOrgResVOList);

        // 放入缓存
        if (null != userOrgResVOList && userOrgResVOList.size() > 0) {
            //String result = JedisUtil.setObjectValue(redisKey, userOrgResVOList, CacheUtil.randomExpireSeconds());
            //log.info("getOrgFromCache redisKey:{},userOrgResVOList:{},result:{}", redisKey, JSON.toJSONString(userOrgResVOList), result);
            CacheUtil.setObjectValueInThread(redisKey, userOrgResVOList);
        }

        // 当前操作组织信息
        SysCurrentOrg sysCurrentOrg = sysCurrentOrgDomain.getByUserId(rpcUserInfoVO.getUserId());
        if (!ObjectUtils.isEmpty(sysCurrentOrg)) {
            String orgCode = sysCurrentOrg.getOrgCode();
            List<String> orgCodeList = userOrgResVOList.stream().map(UserOrgResVO::getOrgCode).collect(Collectors.toList());
            // 如果用户所在组织包含当前组织编码，则设置为当前组织，否则设置默认组织
            if (orgCodeList.contains(orgCode)) {
                rpcUserInfoVO.setCurrentOrgCode(orgCode);
            }
        }
        // 设置默认组织信息
        if (ObjectUtils.isEmpty(rpcUserInfoVO.getCurrentOrgCode()) && !ObjectUtils.isEmpty(primaryOrg.get())) {
            rpcUserInfoVO.setCurrentOrgCode(primaryOrg.get().getOrgCode());
        }
    }

    /**
     * 从缓存获取人员组信息
     */
    private void getUserGroupFromCache(RpcUserInfoVO rpcUserInfoVO) {
        String redisKey = CacheUtil.getUserInfoGroupKey(rpcUserInfoVO.getUserId());
        Object objectValue = JedisUtil.getObjectValue(redisKey);
        if (null != objectValue) {
            List<UserGroupResVO> userGroupList = (List<UserGroupResVO>) objectValue;
            rpcUserInfoVO.setUserGroupList(userGroupList);
            log.info("getUserGroupFromCache 从缓存获取成功");
            return;
        }

        SelectGroupPageRequestVO groupParam = new SelectGroupPageRequestVO();
        groupParam.setEmployeeId(rpcUserInfoVO.getEmployeeInfo().getEmployeeId());
        List<Long> groupIdList = sysGroupDomain.getGroupIdSetByEmployeeCondition(groupParam).stream().collect(Collectors.toList());
        List<SysGroup> sysGroupList = sysGroupDomain.getListByIds(groupIdList);
        List<UserGroupResVO> userGroupList = new ArrayList<>(sysGroupList.size());
        sysGroupList.forEach(sysGroup -> {
            UserGroupResVO userGroup = new UserGroupResVO();
            userGroup.setGroupId(sysGroup.getId());
            userGroup.setGroupName(sysGroup.getGroupName());
            userGroup.setUuid(sysGroup.getUuid());
            userGroupList.add(userGroup);
        });
        rpcUserInfoVO.setUserGroupList(userGroupList);
        // 放入缓存
        if (null != userGroupList && userGroupList.size() > 0) {
            //String result = JedisUtil.setObjectValue(redisKey, userGroupList, CacheUtil.randomExpireSeconds());
            //log.info("getUserGroupFromCache redisKey:{},userGroupList:{},result:{}", redisKey, JSON.toJSONString(userGroupList), result);
            CacheUtil.setObjectValueInThread(redisKey, userGroupList);
        }
    }

    /**
     * 通过缓存查询用户信息
     */
    public BaseResult<RpcUserInfoVO> qryUserInfoFromCache(SelectUserInfoReqVO paramVo) {
        RpcUserInfoVO rpcUserInfoVO = new RpcUserInfoVO();
        //1、检查参数合法性
        if (null == paramVo) {
            return BaseResult.buildError("参数不能为空");
        }
        if (null == paramVo.getUserId() && ObjectUtils.isEmpty(paramVo.getEmployeeCode()) && ObjectUtils.isEmpty(paramVo.getUserAccount())) {
            return BaseResult.buildError("userId/employeeCode/userAccount不能都为空");
        }
        //2、查询用户基本信息
        SysUser sysUser = getSysUserFromCache(paramVo);
        if (ObjectUtils.isEmpty(sysUser)) {
            return BaseResult.buildError("没有查到该用户");
        }
        //3、查询角色信息
        BeanUtils.copyProperties(sysUser, rpcUserInfoVO);
        rpcUserInfoVO.setUserId(sysUser.getId());
        getUserRoleFromCache(rpcUserInfoVO);
        //4、查询员工信息
        getUserEmployeeFromCache(rpcUserInfoVO);
        if (null == rpcUserInfoVO.getEmployeeInfo()) {
            log.info("rpcUserInfoVO.getEmployeeInfo() is null");
            return BaseResult.buildSuccess(rpcUserInfoVO);
        }
        //5、岗位
        getUserPositionFromCache(rpcUserInfoVO);
        //6、组织
        getUserOrgFromCache(rpcUserInfoVO);
        //7、人员组
        getUserGroupFromCache(rpcUserInfoVO);
        return BaseResult.buildSuccess(rpcUserInfoVO);
    }

    @Override
    public BaseResult deleteUserFromCache(CacheRequestVO cacheRequestVO) {
        if (!isOpenQueryUserCacheSwatch()) {
            return BaseResult.buildError(Constants.TIP_CACHE_NOT_OPEN);
        }
        if (null == cacheRequestVO) {
            return BaseResult.buildError("参数不能为空");
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(cacheRequestVO, sysUser);
        sysUserCacheDomain.batchDeleteUserInfoFromCache(Arrays.asList(sysUser));
        return BaseResult.buildSuccess();
    }

    @Override
    public BaseResult batchDeleteUserFromCache(List<CacheRequestVO> cacheRequestVOList) {
        if (!isOpenQueryUserCacheSwatch()) {
            return BaseResult.buildError(Constants.TIP_CACHE_NOT_OPEN);
        }
        if (null == cacheRequestVOList && cacheRequestVOList.size() <= 0) {
            return BaseResult.buildError("参数不能为空");
        }
        List<SysUser> sysUserList = new ArrayList<>();
        BeanUtils.copyProperties(cacheRequestVOList, sysUserList);
        sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList);
        return BaseResult.buildSuccess();
    }

    /**
     * 更新用户信息清理缓存
     */
    public void deleteUserFromCacheByUserUpdate(SysUser user) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (null == user) {
                log.info("deleteUserFromCacheByUserUpdate user is null");
                return;
            }
            sysUserCacheDomain.batchDeleteUserInfoFromCache(Arrays.asList(user));
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByUserUpdate exception", ex);
        }
    }

    /**
     * 删除用户信息清理缓存
     */
    public void deleteUserFromCacheByUserDelete(List<Long> userIdList) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (CollectionUtils.isEmpty(userIdList)) {
                log.info("deleteUserFromCacheByUserDelete userIdList is empty");
                return;
            }
            List<SysUser> sysUserList = sysUserDomain.selectUserListByUserIds(userIdList);
            if (CollectionUtils.isEmpty(sysUserList)) {
                log.info("deleteUserFromCacheByUserDelete sysUserList is empty");
            }
            sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList);
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByUserDelete exception", ex);
        }
    }

    /**
     * 更新或删除员工信息清理缓存
     */
    public void deleteUserFromCacheByEmployeeUpdate(List<Long> employeeIdList) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (CollectionUtils.isEmpty(employeeIdList)) {
                log.info("deleteUserFromCacheByEmployeeDelete employeeIdList is empty");
                return;
            }
            List<SysUser> sysUserList = sysUserDomain.selectUserListByEmployeeIds(employeeIdList);
            if (CollectionUtils.isEmpty(sysUserList)) {
                log.info("deleteUserFromCacheByEmployeeDelete sysUserList is empty");
                return;
            }
            sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList);
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByEmployeeDelete exception", ex);
        }
    }

    /**
     * 更新组织信息清理缓存
     */
    public void deleteUserFromCacheByOrgUpdate(Long orgId) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (null == orgId || orgId <= 0) {
                log.info("deleteUserFromCacheByOrgUpdate orgId is null");
                return;
            }
            List<SysUser> sysUserList = sysUserDomain.selectUserListByOrgIds(Arrays.asList(orgId));
            if (CollectionUtils.isEmpty(sysUserList)) {
                log.info("deleteUserFromCacheByOrgUpdate sysUserList is empty");
                return;
            }
            sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList);
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByOrgUpdate exception", ex);
        }
    }

    /**
     * 删除组织信息清理缓存
     */
    public void deleteUserFromCacheByOrgDelete(Long orgId) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (null == orgId || orgId <= 0) {
                log.info("deleteUserFromCacheByOrgDelete orgId is null");
                return;
            }

            List<SysOrg> orgList = sysOrgDomain.qryChildListByOrgId(orgId + "");
            if (CollectionUtils.isEmpty(orgList)) {
                log.info("deleteUserFromCacheByOrgDelete orgList is empty");
                return;
            }
            List<Long> orgIds = new ArrayList<>();
            orgList.forEach((item) -> {
                if (null != item && null != item.getId()) {
                    orgIds.add(item.getId());
                }
            });
            if (CollectionUtils.isEmpty(orgIds)) {
                log.info("deleteUserFromCacheByOrgDelete orgIds is empty");
                return;
            }

            List<SysUser> sysUserList = sysUserDomain.selectUserListByOrgIds(orgIds);
            if (CollectionUtils.isEmpty(sysUserList)) {
                log.info("deleteUserFromCacheByOrgDelete sysUserList is empty");
                return;
            }
            sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList);
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByOrgDelete exception", ex);
        }
    }

    /**
     * 更新岗位信息清理缓存
     */
    public void deleteUserFromCacheByPositionUpdate(Long positionId) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (null == positionId || positionId <= 0) {
                log.info("deleteUserFromCacheByPositionUpdate positionId is null");
                return;
            }
            List<SysUser> sysUserList = sysUserDomain.selectUserListByPositionIds(Arrays.asList(positionId));
            if (CollectionUtils.isEmpty(sysUserList)) {
                log.info("deleteUserFromCacheByPositionUpdate sysUserList is empty");
                return;
            }
            sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList, Sets.newHashSet(CacheUtil.REDIS_KEY_USER_INFO_POSITION));
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByPositionUpdate exception", ex);
        }
    }

    /**
     * 更新角色信息清理缓存
     */
    public void deleteUserFromCacheByRoleUpdate(Long roleId) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (null == roleId || roleId <= 0) {
                log.info("deleteUserFromCacheByRoleUpdate roleId is null");
                return;
            }
            List<SysUser> sysUserList = sysUserDomain.selectUserListByRoleIds(Arrays.asList(roleId));
            if (CollectionUtils.isEmpty(sysUserList)) {
                log.info("deleteUserFromCacheByRoleUpdate sysUserList is empty");
                return;
            }
            sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList, Sets.newHashSet(CacheUtil.REDIS_KEY_USER_INFO_ROLE));
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByRoleUpdate exception", ex);
        }
    }

    /**
     * 更新用户组信息清理缓存
     */
    public void deleteUserFromCacheByGroupUpdate(Long groupId) {
        try {
            if (!isOpenQueryUserCacheSwatch()) {
                log.info(Constants.TIP_CACHE_NOT_OPEN);
                return;
            }

            if (null == groupId || groupId <= 0) {
                log.info("deleteUserFromCacheByGroupUpdate roleId is null");
                return;
            }
            List<SysUser> userList = new ArrayList<>();
            // 处理关联的员工
            List<SysUser> empUserList = sysUserDomain.selectUserListByGroupIds(Arrays.asList(groupId));
            if (!CollectionUtils.isEmpty(empUserList)) {
                userList.addAll(empUserList);
            }
            // 处理关联的组织及下层组织
            List<SysOrgGroup> orgGroupList = sysOrgGroupDomain.selectOrgGroupListByGroupIds(Arrays.asList(groupId), "");
            if (!CollectionUtils.isEmpty(orgGroupList)) {
                List<SysOrg> orgList = null;
                for (SysOrgGroup sysOrgGroup : orgGroupList) {
                    orgList = sysOrgDomain.qryChildListByOrgId(sysOrgGroup.getOrgId() + "");
                    if (!CollectionUtils.isEmpty(orgList)) {
                        List<Long> orgIds = new ArrayList<>();
                        orgList.forEach(item -> {
                            orgIds.add(item.getId());
                        });
                        List<SysUser> orgUserList = sysUserDomain.selectUserListByOrgIds(orgIds);
                        if (!CollectionUtils.isEmpty(orgUserList)) {
                            userList.addAll(orgUserList);
                        }
                    }
                }
            }

            if (CollectionUtils.isEmpty(userList)) {
                log.info("deleteUserFromCacheByGroupUpdate userList is empty");
                return;
            }
            userList = userList.stream().distinct().collect(Collectors.toList());
            sysUserCacheDomain.batchDeleteUserInfoFromCache(userList, org.apache.commons.compress.utils.Sets.newHashSet(CacheUtil.REDIS_KEY_USER_INFO_GROUP));
        } catch (Exception ex) {
            log.error("deleteUserFromCacheByGroupUpdate exception", ex);
        }
    }

    /**
     * 对于删除失败的情况做重新删除
     */
    public void reDeleteUserInfoFromCache() {
        if (!isOpenQueryUserCacheSwatch()) {
            log.info(Constants.TIP_CACHE_NOT_OPEN);
            return;
        }
        SysUserCache sysUserCache = new SysUserCache();
        sysUserCache.setStatus(SysUserCacheStatusEnum.INIT.getValue());
        List<SysUserCache> sysUserCacheList = sysUserCacheDomain.listByPara(sysUserCache, null);
        if (CollectionUtils.isEmpty(sysUserCacheList)) {
            log.info("reDeleteUserInfoFromCache sysUserCacheList is empty");
            return;
        }

        for (SysUserCache item : sysUserCacheList) {
            //乐观锁锁定
            item.setStatus(SysUserCacheStatusEnum.ING.getValue());
            item.setGmtModified(LocalDateTime.now());
            item.setOriStatus(SysUserCacheStatusEnum.INIT.getValue());
            int iRtn = sysUserCacheDomain.updateByIdAndStatus(item);
            if (iRtn < 1) {
                log.info("reDeleteUserInfoFromCache update {} to ing failure, maybe updated by other", item.getId());
                continue;
            } else {
                log.info("reDeleteUserInfoFromCache update {} to ing success", item.getId());
            }

            //执行删除
            if (null != item.getUserId()) {
                List<SysUser> sysUserList = sysUserDomain.selectUserListByUserIds(Arrays.asList(item.getUserId()));
                if (!CollectionUtils.isEmpty(sysUserList)) {
                    sysUserCacheDomain.batchDeleteUserInfoFromCache(sysUserList);
                }
                item.setStatus(SysUserCacheStatusEnum.SUCCESS.getValue());
            } else if (StringUtils.isNotEmpty(item.getCacheKey())) {
                Long lRtn = JedisUtil.checkExistsAndDel(item.getCacheKey());
                log.info("checkExistsAnddel key:{}, result:{}", item.getCacheKey(), iRtn);
                item.setStatus(0 != lRtn ? SysUserCacheStatusEnum.SUCCESS.getValue() : SysUserCacheStatusEnum.FAILURE.getValue());
            }

            //执行更新
            item.setOriStatus(SysUserCacheStatusEnum.ING.getValue());
            item.setGmtCreated(LocalDateTime.now());
            iRtn = sysUserCacheDomain.updateByIdAndStatus(item);
            if (iRtn > 0) {
                log.info("reDeleteUserInfoFromCache update {} to {} success", item.getId(), item.getStatus());
            } else {
                log.info("reDeleteUserInfoFromCache update {} to {} failure, maybe updated by other", item.getId(), item.getStatus());
            }
        }
    }
}
